// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import GameConfig, { BlockData, COLOR } from "../GameConfig";
import Utlis from "../Utlis";

const {ccclass, property} = cc._decorator;

@ccclass
export default class BlockGridRender {

    private nodeList:Array<cc.Node> = new Array<cc.Node>();
    private render:cc.Node = null;
    private prefab:cc.Prefab = null;

    constructor(render:cc.Node) {
        this.render = render;
        Utlis.loadPrefab(GameConfig.BIG_BLOCK_PREFAB).then((prefab)=>{
            this.prefab = prefab;
        })
    }


    private createBlockRender(block:BlockData) {
        if (block.color == COLOR.Null) {
            return null;
        }
        const designSize = cc.view.getDesignResolutionSize();
        // if (this.prefab == null) {
        //     this.prefab = await Utlis.loadPrefab(GameConfig.BIG_BLOCK_PREFAB);
        // }
        const node:cc.Node = cc.instantiate(this.prefab);
        node.setPosition(block.x*GameConfig.BIG_BLOCK_SIZE-designSize.width/2, block.y*GameConfig.BIG_BLOCK_SIZE-designSize.height/2);
        node.color = GameConfig.getColor(block.color);
        this.render.addChild(node);
        return node;
    }

    private clearBlockRender() {
        for (let i = 0; i < this.nodeList.length; i++) {
            this.nodeList[i].destroy();
        }
        this.nodeList.length = 0;
    }

    public async updateGridRender(bigBlockGrid:BlockData[][]) {
        this.clearBlockRender();
        for (let y = 0; y < bigBlockGrid.length; y++) {
            for (let x = 0; x < bigBlockGrid[y].length; x++) {
                const block = bigBlockGrid[y][x];
                const node = this.createBlockRender(block);
                if (node) {
                    this.nodeList.push(node);
                }
            }
        }
    }
}
